import type { Settings as LayoutSettings } from '@ant-design/pro-layout';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import type { RequestConfig } from 'umi';
import type { RequestInterceptor } from 'umi-request';
import type { ResponseInterceptor } from 'umi-request';
import type { ResponseError } from 'umi-request';
import { PageLoading } from '@ant-design/pro-layout';
import type { RunTimeLayoutConfig } from 'umi';
import { history } from 'umi';
import RightContent from '@/components/RightContent';
// import Footer from '@/components/Footer';
import { getInfo, getRouters, refreshToken } from './services/common/index';
import { notification, message, Modal } from 'antd';

const { confirm } = Modal;
// const isDev = process.env.NODE_ENV === 'development';
const loginPath = '/user/login/';
const whiteList: string[] = ['/api/v1/sendMailer', '/api/v1/admin_users/login'];

/** 获取用户信息比较慢的时候会展示一个 loading */
export const initialStateConfig = {
  loading: <PageLoading />,
};

const codeMessage = {
  200: '服务器成功返回请求的数据。',
  201: '新建或修改数据成功。',
  202: '一个请求已经进入后台排队（异步任务）。',
  204: '删除数据成功。',
  400: '发出的请求有错误，服务器没有进行新建或修改数据的操作。',
  401: '用户没有权限（令牌、用户名、密码错误）。',
  403: '用户得到授权，但是访问是被禁止的。',
  404: '发出的请求针对的是不存在的记录，服务器没有进行操作。',
  405: '请求方法不被允许。',
  406: '请求的格式不可得。',
  410: '请求的资源被永久删除，且不会再得到的。',
  422: '当创建一个对象时，发生一个验证错误。',
  500: '服务器发生错误，请检查服务器。',
  502: '网关错误。',
  503: '服务不可用，服务器暂时过载或维护。',
  504: '网关超时。',
};

const headerInfo: RequestInterceptor = (url: string, options: RequestInit) => {
  if (localStorage.getItem('token') && !whiteList.includes(url)) {
    const token = localStorage.getItem('token');
    options.headers = {
      ...options.headers,
      authorization: `${token}`
    };
  }
  return { url, options };
};

const responseInfo: ResponseInterceptor = async (response: Response) => {
  const data = await response.clone().json();
  // 在其他地方登录，刷新token
  if (data.code === 405) {
    confirm({
      title: '提示',
      icon: <ExclamationCircleOutlined />,
      content: `${data.msg}?`,
      onOk: async () => {
        const rsp = await refreshToken();
        if (rsp.code === 0) {
          await localStorage.setItem('token', rsp.data);
          await window.location.reload();
        }
      },
      onCancel() {
        localStorage.removeItem('token');
        history.push(loginPath);
      },
    });
  } else if (data.code === 403) {
    message.destroy();
    message.error(data.msg);
    history.push(loginPath);
  } else if (![405, 403, 0].includes(data.code)) {
    message.destroy();
    message.error(data.msg || '操作失败');
  }
  return data;
};

/**
 * 异常处理程序
 */
const errorHandler = (error: ResponseError) => {
  const { response } = error;
  if (response && response.status) {
    const errorText = codeMessage[response.status] || response.statusText;
    const { status, url } = response;

    notification.error({
      message: `请求错误 ${status}: ${url}`,
      description: errorText,
    });
  }

  if (!response) {
    notification.error({
      description: '您的网络发生异常，无法连接服务器',
      message: '网络异常',
    });
  }
  throw error;
};

export const request: RequestConfig = {
  errorHandler,
  credentials: 'include',
  requestInterceptors: [headerInfo],
  responseInterceptors: [responseInfo],
};

/**
 * @see  https://umijs.org/zh-CN/plugins/plugin-initial-state
 * */
export async function getInitialState(): Promise<{
  settings?: Partial<LayoutSettings>;
  currentUser?: COMMON_API.UserInfo;
  sysSettings?: COMMON_API.Settings;
  allMenuList?: COMMON_API.Menu[];
  menuList?: COMMON_API.Menu[];
  hasRoute?: string[];
  permsList?: string[];
  fetchUserInfo?: () => Promise<COMMON_API.CurrentUser | undefined>;
  fetchRouters?: () => Promise<COMMON_API.Routers | undefined>;
}> {
  const fetchUserInfo = async () => {
    try {
      const rsp = await getInfo();
      return rsp.data;
    } catch (error) {
      history.push(loginPath);
    }
    return undefined;
  };
  const fetchRouters = async () => {
    try {
      const rsp = await getRouters();
      return rsp.data;
    } catch (error) {
      history.push(loginPath);
    }
    return undefined;
  };
  // 如果是登录页面，不执行
  
  if (location.pathname !== loginPath) {
    const info = await fetchUserInfo();
    const routers = await fetchRouters();
    return {
      fetchUserInfo,
      fetchRouters,
      currentUser: info?.userInfo,
      sysSettings: info?.settings,
      menuList: routers?.menuList,
      hasRoute: routers?.hasRoute,
      permsList: routers?.permsList,
      allMenuList: routers?.allMenuList,
      settings: {},
    };
  }
  return {
    fetchUserInfo,
    fetchRouters,
    settings: {},
  };
}

// ProLayout 支持的api https://procomponents.ant.design/components/layout
export const layout: RunTimeLayoutConfig = ({ initialState }) => {
  return {
    rightContentRender: () => <RightContent />,
    disableContentMargin: false,
    waterMarkProps: {
      content: initialState?.currentUser?.user_no,
    },
    footerRender: () => null,
    onPageChange: () => {
      const { location } = history;
      // 如果没有登录，重定向到 login
      if (!initialState?.currentUser && location.pathname !== loginPath) {
        history.push(loginPath);
      }
    },
    // menuDataRender: () => fixMenuItemIcon(initialState?.menuList || []),
    menuDataRender: () => initialState?.menuList || [],
    menuHeaderRender: undefined,
    iconfontUrl: initialState?.sysSettings?.iconfontUrl,
    logo: initialState?.sysSettings?.logo && initialState?.sysSettings?.logo.startsWith('http') ? 
    initialState.sysSettings.logo : window.location.protocol + '//' + window.location.host + ':7001' + initialState?.sysSettings?.logo,
    title: initialState?.sysSettings?.title,
    // 自定义 403 页面
    // unAccessible: <div>unAccessible</div>,
    // 增加一个 loading 的状态
    // childrenRender: (children) => {
    //   if (initialState.loading) return <PageLoading />;
    //   return children;
    // },
    ...initialState?.settings,
  };
};
